package com.dosen.api.third.party.register.result.argocd.result;


import cn.hutool.core.lang.Assert;
import lombok.Data;

import java.io.Serializable;

/**
 * @version V1.0
 * @author: guangcheng
 * @date: 2022/5/6 20:04
 * @description:
 */
@Data
public class Result<T> implements Serializable {
    private static final long serialVersionUID = 1L;


    private static Integer SUCCESS_CODE = 200;
    private static Integer ERROR_CODE = 500;
    private boolean success;
    private String message;
    private Integer code;
    private long timestamp = System.currentTimeMillis();
    private T data;

    public static <T> Result<T> success(T data) {
        return buildResult(true, SUCCESS_CODE, "操作成功", data);
    }

    public static <T> Result<T> success() {
        return buildResult(true, SUCCESS_CODE, "操作成功", null);
    }

    public static <T> Result<T> error(Integer code, String message) {
        Assert.isTrue(!SUCCESS_CODE.equals(code), "code 必须是错误的！", new Object[0]);
        return buildResult(false, code, message, null);
    }

    public static <T> Result<T> error(Result<?> result) {
        return error(result.getCode(), result.getMessage());
    }

    public static <T> Result<T> error(String message) {
        return buildResult(false, ERROR_CODE, message, null);
    }

    public static <T> Result<T> error(BaseErrorCode errorCode) {
        return buildResult(false, errorCode.getCode(), errorCode.getMessage(), null);
    }

    public static <T> Result<T> error(BusinessException exception) {
        return buildResult(false, exception.getCode(), exception.getMessage(), null);
    }

    private static <T> Result<T> buildResult(boolean success, Integer code, String msg, T obj) {
        Result<T> r = new Result();
        r.setSuccess(success);
        r.setCode(code);
        r.setMessage(msg);
        r.setData(obj);
        return r;
    }
}

